package cn.sjx.graduate.service.impl;

import cn.sjx.graduate.domain.Employee;
import cn.sjx.graduate.domain.LeaveList;
import cn.sjx.graduate.domain.Staff;
import cn.sjx.graduate.mapper.LeaveMapper;
import cn.sjx.graduate.qo.QueryObject;
import cn.sjx.graduate.service.IEmployeeService;
import cn.sjx.graduate.service.ILeaveService;
import cn.sjx.graduate.service.IStaffService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bo-feifei
 * @since 2022-05-05
 */
@Service
public class LeaveServiceImpl extends ServiceImpl<LeaveMapper, LeaveList> implements ILeaveService {


    @Autowired
    private IStaffService staffService;
    @Autowired
    private IEmployeeService employeeService;

    @Override
    public IPage<LeaveList> queryPage(QueryObject qo, Employee employee) {
        Boolean admin = employee.getAdmin();
        IPage<LeaveList> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        QueryWrapper<LeaveList> query = Wrappers.query();
        if (!admin) {
            query.eq("leave_employee_id", employee.getId());
        }
        query.orderByDesc("create_time");
        IPage<LeaveList> page1 = super.page(page, query);
        List<LeaveList> records = page1.getRecords();
        for (int i = 0; i < records.size(); i++) {
            LeaveList leaveList = records.get(i);
            Long leaveEmployeeId = leaveList.getLeaveEmployeeId();
            Employee employee1 = employeeService.getById(leaveEmployeeId);
            leaveList.setEmployeeNickName(employee1.getNickname());
        }
        int size = records.size();
        String s = String.valueOf(size);
        page1.setTotal(Long.parseLong(s));
        return page1;
    }

    @Override
    @Transactional
    public void checkLeaveApply(LeaveList leaveList) {
        Long leaveId = leaveList.getId();
        LeaveList leave = getById(leaveId);
        Long employeeId = leave.getLeaveEmployeeId();
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("employee_id",employeeId);
        Staff staff = staffService.getOne(queryWrapper);
        staff.setLeaveHours(leave.getHours());

        leave.setCheckResult(leaveList.getCheckResult());
        leave.setCheckState(leaveList.getCheckState());
        this.updateById(leave);
        staffService.updateById(staff);
    }
}
